package hu.diploma.android.threads;

import hu.diploma.android.ContactManagerClient;
import hu.diploma.android.R;
import hu.diploma.android.util.ServiceProviderImpl;
import hu.diploma.android.util.database.DeviceUtil;
import hu.diploma.common.resource.CallResource;
import hu.diploma.common.resource.DeviceResource;
import hu.diploma.common.resource.SmsMmsResource;
import hu.diploma.common.service.CallsService;
import hu.diploma.common.service.DeviceService;
import hu.diploma.common.service.GroupService;
import hu.diploma.common.service.SmsMmsService;
import hu.diploma.common.vos.CallVo;
import hu.diploma.common.vos.DeviceVo;
import hu.diploma.common.vos.GroupVo;
import hu.diploma.common.vos.SmsMmsVo;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.restlet.resource.ClientResource;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

public class ContactManagerService extends Service {
	private static final int INTERVAL = 30 * 60 * 1000;
	private NotificationManager notificationManager;
	private final IBinder binder = new LocalBinder();
	private final int NOTIFICATION = 0;
	private final int NOTIFICATION_IN_PROGRESS = 1;
	private final int NOTIFICATION_SUCCES = 2;
	private final int NOTIFICATION_ERROR = 3;
	private SharedPreferences settings;

	public class LocalBinder extends Binder {
		public ContactManagerService getService() {
			return ContactManagerService.this;
		}
	}

	@Override
	public void onCreate() {
		notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		settings = getSharedPreferences(ServiceProviderImpl.PREFS_NAME, MODE_WORLD_WRITEABLE);
	}

	@Override
	public IBinder onBind(Intent intent) {

		return binder;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if (settings.getBoolean("auto_sync", true)) {
			startTimer();
		}

		return START_STICKY;
	}

	public void synchronisation() {
		showNotification(NOTIFICATION_IN_PROGRESS);

		DeviceService deviceService = ServiceProviderImpl.getInstance().getDeviceService();
		GroupService groupService = ServiceProviderImpl.getInstance().getGroupService();
		CallsService callsService = ServiceProviderImpl.getInstance().getCallService();
		SmsMmsService smsMmsService = ServiceProviderImpl.getInstance().getSmsMmsService();
		Log.e("DEBUG", "getContentResolver : " + ServiceProviderImpl.getInstance().getContentResolver());
		try {
			String url = settings.getString("set_url", "http://192.168.1.64:8888/restlet/");

			if (settings.getBoolean("contact_sync", true)) {

				ClientResource cr = new ClientResource(url + DeviceResource.URL);

				DeviceResource resource = cr.wrap(DeviceResource.class);
				List<GroupVo> groupVos = groupService.loadAll();
				DeviceVo deviceVo = DeviceUtil.loadDevice();
				deviceVo.setGroups(groupVos);
				DeviceVo resultDeviceVo = resource.merge(deviceVo);
				deviceService.merge(resultDeviceVo);

			}
			if (settings.getBoolean("call_sync", true)) {
				ArrayList<CallVo> callVos = (ArrayList<CallVo>) callsService.loadAll();
				ServiceProviderImpl.getInstance().setCallVos(callVos);
				ClientResource cr = new ClientResource(url + DeviceResource.URL);

				CallResource resource = cr.wrap(CallResource.class);
				resource.merge(callVos);
			}
			if (settings.getBoolean("sms_sync", true)) {
				ClientResource cr = new ClientResource(url + DeviceResource.URL);

				SmsMmsResource resource = cr.wrap(SmsMmsResource.class);

				ArrayList<SmsMmsVo> smsMmsVos = (ArrayList<SmsMmsVo>) smsMmsService.loadAll();
				ServiceProviderImpl.getInstance().setSmsMmsVos(smsMmsVos);
				resource.merge(smsMmsVos);
			}

			SharedPreferences.Editor editor = settings.edit();
			editor.putLong("last_sync_date", new Date().getTime());
			notificationManager.cancel(NOTIFICATION);
			showNotification(NOTIFICATION_SUCCES);
		} catch (Exception e) {
			notificationManager.cancel(NOTIFICATION);
			showNotification(NOTIFICATION_SUCCES);
			Log.e("DEBUG", e.getMessage(), e);

		}
	}

	@Override
	public void onDestroy() {
		notificationManager.cancel(NOTIFICATION);
	}

	/**
	 * Show a notification while this service is running.
	 */
	private void showNotification(int id) {
		Notification notification = null;
		switch (id) {
		case NOTIFICATION_IN_PROGRESS: {

			String inProgress = getResources().getString(R.string.notifi_in_progres);
			notification = new Notification(R.drawable.cm, inProgress, System.currentTimeMillis());
			PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this,
					ContactManagerClient.class), 0);
			notification.setLatestEventInfo(this, getText(R.string.app_name), inProgress, contentIntent);
			RemoteViews progress = new RemoteViews(getPackageName(), R.layout.progress);
			notification.contentView = progress;
		}
			break;
		case NOTIFICATION_SUCCES: {
			String succes = getResources().getString(R.string.notifi_succes);
			notification = new Notification(R.drawable.cm, succes, System.currentTimeMillis());
			PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this,
					ContactManagerClient.class), 0);
			notification.setLatestEventInfo(this, getText(R.string.app_name), succes, contentIntent);

			notification.sound = Uri.parse(settings.getString("notification_ringstone", null));
		}
			break;
		case NOTIFICATION_ERROR: {
			String string = getResources().getString(R.string.notifi_error);
			notification = new Notification(R.drawable.cm, string, System.currentTimeMillis());
			PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this,
					ContactManagerClient.class), 0);
			notification.setLatestEventInfo(this, getText(R.string.app_name), string, contentIntent);

		}
		}

		notificationManager.notify(NOTIFICATION, notification);
	}

	private static long DELAY_INTERVAL = 0;
	private static long UPDATE_INTERVAL = 24 * 60 * 60 * 1000; // default
	private Timer timer;

	public void stopTimer() {
		if (timer != null) {
			timer.cancel();
		}
	}

	public void startTimer() {
		timer = new Timer();
		timer.scheduleAtFixedRate(

		new TimerTask() {

			@Override
			public void run() {

				try {

					ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
					NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

					Thread.sleep(getFrequncy());

					if (mWifi.isConnected()) {
						synchronisation();
					} else {
						Log.d("DEBUG", "UPDATE_INTERVAL ");
						setFrequency(INTERVAL);
						timer.cancel();
						startTimer();
					}

				} catch (Exception e) {
					Log.e("DEBUG", e.getMessage(), e);
				}

			}
		}, 0, getFrequncy());
	}

	public static void setFrequency(long uPDATE_INTERVAL) {
		UPDATE_INTERVAL = uPDATE_INTERVAL;
	}

	public static long getFrequncy() {
		return UPDATE_INTERVAL;
	}
}